# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://pay.payfubao.com/sdk_transform/wap_api'
_WX_GATEWAY = 'http://pay.payfubao.com/sdk_transform/wx_wap_api'
_QUERY_GATEWAY = 'http://pay.payfubao.com/ali_pay/merchantsearch'

APP_CONF = {
    '11248': {
        'API_KEY': '7e725be3e58d335bb3c77c629d056af3'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = '{}{}{}{}{}'.format(
        parameter['para_id'], parameter['app_id'], parameter['order_no'],
        parameter['total_fee'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info(u'payfubao origin string: %s, sign:%s', s, sign)
    return sign


def generate_query_sign(parameter, key):
    '''  生成查询签名 '''
    s = '{}{}{}{}'.format(
        parameter['para_id'], parameter['app_id'], parameter['order_no'],
        key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info(u'payfubao origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    s = '{}{}{}'.format(params['orderno'], params['fee'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("payfubao sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    '''创建订单'''
    charge_resp = {}
    service = info['service']  # wechat or alipay
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    if service == 'wechat':
        try:
            extra = json.loads(info['extra'])
        except:
            extra = {}
        user_info = extra.get('user_info', {})
        device_ip = user_info.get('device_ip') or '112.224.1.65'
        p_dict = OrderedDict((
            ('body', 'test'),
            ('total_fee', int(pay_amount * 100)),
            ('para_id', app_id),
            ('app_id', '11303'),
            ('order_no', str(pay.id)),
            ('attach', '{}'),
            ('type', '2'),
            ('child_para_id', '1'),
            ('device_id', '1'),
            ('mch_create_ip', '112.224.1.65'),  # FIXME should use `device_ip`
            ('mch_app_id', 'http://'),
            ('mch_app_name', 'ddz'),
            ('notify_url', '{}/pay/api/{}/payfubao/{}'.format(
                settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
            ('returnurl', '{}/pay/api/{}/payfubao/{}/'.format(
                settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ))
        gate_url = _WX_GATEWAY
    else:
        p_dict = OrderedDict((
            ('body', 'goods'),
            ('total_fee', int(pay_amount * 100)),
            ('para_id', app_id),
            ('app_id', '11303'),
            ('order_no', str(pay.id)),
            ('attach', '{}'),
            ('type', '1'),
            ('child_para_id', '1'),
            ('device_id', '1'),
            ('notify_url', '{}/pay/api/{}/payfubao/{}'.format(
                settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
            ('callback_url', '{}/pay/api/{}/payfubao/{}/'.format(
                settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ))
        gate_url = _GATEWAY
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    p_dict['sign'] = generate_sign(p_dict, api_key)
    response = requests.post(gate_url, data=p_dict, headers=headers, timeout=3)
    _LOGGER.info(u'payfubao create charge: %s %s', p_dict, response.text)
    data = json.loads(response.text)
    charge_resp.update({
        'charge_info': data['pay_url'],
    })
    return charge_resp


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("payfubao notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderno']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('payfubao event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = '1'
    trade_no = data.get('wxno')
    total_fee = float(data['fee']) / 100

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('payfubao check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    service_name = 'alipay'
    if service_name == 'wechat':
        pay_type = 1
    else:
        pay_type = 2
    p_dict = OrderedDict((
        ('para_id', app_id),
        ('app_id', '11303'),
        ('order_no', str(pay_order.id)),
        ('pay_type', pay_type),
        ('device_id', '1'),
    ))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    p_dict['sign'] = generate_query_sign(p_dict, api_key)
    response = requests.post(_QUERY_GATEWAY, data=p_dict, headers=headers, timeout=3)
    _LOGGER.info(u'payfubao create charge: %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = int(data['status'])
        if trade_status == 1:
            trade_no = data['ali_trade_no']
            total_fee = float(data['total_fee']) / 100
            extend = {
                'trade_status': trade_status,
                'trade_no': trade_no,
                'total_fee': total_fee
            }
            _LOGGER.info('payfubao query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
